package com.njupt.Tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/12/5 16:21
 * @Description: 98. 验证二叉搜索树
 * @Version: 1.0
 */


public class IsValidBST {

    private long minVal = Long.MIN_VALUE;
    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        boolean left = isValidBST(root.left);   //左
        if(this.minVal < root.val){             //根
            this.minVal = root.val;
        }else {
            return false;
        }
        boolean right = isValidBST(root.right); //右

       return left && right;

    }

    public boolean isValidBST1(TreeNode root) {

        List<Integer> results = new ArrayList<>();
        traverse(root,results);
        return isListSorted(results);

    }

    private boolean isListSorted(List<Integer> results) {

        if(results.size()<=1){
            return true;
        }
        for (int i = 0; i < results.size()-1; i++) {
            if(results.get(i)>= results.get(i+1)){
                return false;
            }
        }
        return true;

//        return results.stream().reduce((pre,rear)->{
//            if(pre>=rear){
//                return Integer.MAX_VALUE;
//            }
//            return rear;
//        }).map(result-> result != Integer.MAX_VALUE ).orElse(true);
    }

    private void traverse(TreeNode root, List<Integer> results) {

        if(root == null) return;
        traverse(root.left,results);
        results.add(root.val);
        traverse(root.right,results);
    }

    public static void main(String[] args) {
//        TreeNode root = new TreeNode(2);
//        root.left = new TreeNode(2);
//        root.right = new TreeNode(2);


//        TreeNode root = new TreeNode(5);
//        root.left = new TreeNode(1);
//        root.right = new TreeNode(4);
//        root.right.left = new TreeNode(3);
//        root.right.right = new TreeNode(6);

        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(1);
        root.right = new TreeNode(6);
        root.right.left = new TreeNode(2);
        root.right.right = new TreeNode(7);
        IsValidBST test = new IsValidBST();
        System.out.println(test.isValidBST(root));
    }
}
